package com.djk.service.impl;

import com.djk.constants.SessionKeys;
import com.djk.mapper.MusicMapper;
import com.djk.pojo.Music;
import com.djk.pojo.User;
import com.djk.service.LovemusicService;
import com.djk.mapper.LovemusicMapper;
import com.djk.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 联想
 * @description 针对表【lovemusic】的数据库操作Service实现
 * @createDate 2024-02-19 22:45:43
 */
@Service
public class LovemusicServiceImpl implements LovemusicService {
    @Autowired
    private LovemusicMapper lovemusicMapper;
    @Autowired
    private MusicMapper musicMapper;

    @Override
    public Result addMyLove(Integer musicId, HttpSession session) {
        //参数校验
        if (musicId == null || musicId <= 0) {
            return Result.error("请求参数错误！");
        }
        //判断musicid是否存在
        Music music = musicMapper.queryById(musicId);
        if (music == null) {
            return Result.error("该资源不存在，无法收藏！");
        }
        User user = (User) session.getAttribute(SessionKeys.USER_INFO_SESSION);
        Integer userId = user.getId();

        //1.查询是否已经收藏过改歌曲
        Integer rows = lovemusicMapper.queryLovemusic(userId, musicId);
        if (rows != null) {
            //2.已收藏直接返回
            return Result.error("你已经收藏过该歌曲了！");
        }
        //3.未收藏，则正常进行
        rows = lovemusicMapper.addLovemusic(userId, musicId);
        if (rows == null) {
            return Result.error("收藏失败！");
        }
        return Result.ok();
    }

    /**
     * 移除我的喜欢/收藏
     *
     * @param musicId
     * @param session
     * @return
     */
    @Override
    public Result deleteMyLove(Integer musicId, HttpSession session) {
        //参数校验
        if (musicId == null || musicId <= 0) {
            return Result.error("请求参数错误！");
        }
        User user = (User) session.getAttribute(SessionKeys.USER_INFO_SESSION);
        Integer userId = user.getId();

        int rows = lovemusicMapper.deleteLovemusic(userId, musicId);
        if (rows <= 0) {
            return Result.error("移除收藏失败！");
        }

        return Result.ok();
    }

    //模糊查询
    @Override
    public Result findMyLove(String musicName, HttpSession session) {
        User user = (User) session.getAttribute(SessionKeys.USER_INFO_SESSION);
        Integer userId = user.getId();
        List<Music> musicList = new ArrayList<>();
        if (musicName != null) {
            musicList = lovemusicMapper.queryLovemusicByName(userId,musicName);
        }else{
            musicList = lovemusicMapper.queryAllMyLove(userId);
        }
        return Result.ok(musicList);
    }
}




